package com.familyaccount.servlet;

import com.familyaccount.model.User;
import com.familyaccount.service.UserService;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/profile")
public class ProfileServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("index.jsp");
            return;
        }
        request.setAttribute("user", session.getAttribute("user"));
        request.getRequestDispatcher("profile.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("index.jsp");
            return;
        }
        User user = (User) session.getAttribute("user");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        user.setName(name);
        user.setEmail(email);
        try {
            userService.updateUser(user);
            if (password != null && !password.isEmpty()) {
                userService.updatePassword(user.getId(), password);
            }
            session.setAttribute("user", userService.getUserById(user.getId()));
            request.setAttribute("user", session.getAttribute("user"));
            request.setAttribute("success", "信息修改成功！");
        } catch (SQLException e) {
            request.setAttribute("error", "信息修改失败，请重试。");
        }
        request.getRequestDispatcher("profile.jsp").forward(request, response);
    }
} 